package org.lanyu.springainovel.common.controller;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.common.vo.RestVO;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理�? * 统一处理系统中的各种异常情况
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理用户名不存在异常
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public RestVO<?> handleUsernameNotFoundException(UsernameNotFoundException ex) {
        return RestVO.fail(401, "用户不存�? " + ex.getMessage());
    }

    /**
     * 处理认证失败异常
     */
    @ExceptionHandler(BadCredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public RestVO<?> handleBadCredentialsException(BadCredentialsException ex) {
        return RestVO.fail(401, "用户名或密码错误");
    }

    /**
     * 处理JWT令牌解析失败异常
     */
    @ExceptionHandler(SignatureException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public RestVO<?> handleSignatureException(SignatureException ex) {
        return RestVO.fail(401, "JWT令牌无效或已过期");
    }

    /**
     * 处理JWT令牌过期异常
     */
    @ExceptionHandler(ExpiredJwtException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public RestVO<?> handleExpiredJwtException(ExpiredJwtException ex) {
        return RestVO.fail(401, "JWT令牌已过期，请重新登陆");
    }

    /**
     * 处理JWT令牌不支持的异常
     */
    @ExceptionHandler(UnsupportedJwtException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public RestVO<?> handleUnsupportedJwtException(UnsupportedJwtException ex) {
        return RestVO.fail(401, "不支持的JWT令牌");
    }

    /**
     * 处理JWT令牌格式错误异常
     */
    @ExceptionHandler(MalformedJwtException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public RestVO<?> handleMalformedJwtException(MalformedJwtException ex) {
        return RestVO.fail(401, "JWT令牌格式错误");
    }

    /**
     * 处理系统通用异常
     */
    @ExceptionHandler({RuntimeException.class, Exception.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public RestVO<?> handleGeneralException(Exception ex) {
        log.error("系统发生异常: ", ex);
        return RestVO.fail("系统内部错误: " + ex.getMessage());
    }
}
